<template>
  <div class="container">
    <Breadcrumb :items="['群组管理', '群组管理']" />
    <!-- 这是分页查询展示的内容 用一个v-if判断了 我是真的聪明 -->
    <a-card v-if="mainVisible == true" class="general-card" title="群组管理">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="number" label="名称">
                  <a-input
                    v-model="formModel.number"
                    placeholder="请输入名称……"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 42px" direction="vertical" />
        <a-col :flex="'192px'" style="text-align: right">
          <a-space direction="horizontal" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <!-- 这里是新建 -->

            <a-button type="primary" @click="handleCreate">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
            <!-- <a-upload action="/">
              <template #upload-button>
                <a-button>
                  {{ $t('searchTable.operation.import') }}
                </a-button>
              </template>
            </a-upload> -->
          </a-space>
        </a-col>
        <!-- <a-col :span="8" style="text-align: right">
          <a-button>
            <template #icon>
              <icon-download />
            </template>
            {{ $t('searchTable.operation.download') }}
          </a-button>
        </a-col> -->
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :bordered="false"
        stripe="true"
        @page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="名称" data-index="groupname" />
          <a-table-column title="描述" data-index="description" />
          <!-- <a-table-column title="昵称" data-index="nickname"> -->
          <!-- </a-table-column> -->
          <!-- <a-table-column title="手机号" data-index="mobile"> -->
          <!-- </a-table-column> -->
          <!-- <a-table-column title="邮箱" data-index="email" /> -->
          <!-- <a-table-column title="创建时间" data-index="createDate" /> -->
          <a-table-column
            :title="$t('searchTable.columns.operations')"
            data-index="operations"
          >
            <template #cell="record">
              <a-button
                type="text"
                status="warning"
                size="small"
                @click="handleModify(record)"
              >
                修改
              </a-button>

              <a-button
                type="text"
                status="danger"
                size="small"
                @click="deleteGroupButton(record)"
              >
                删除
              </a-button>

              <a-button
                type="text"
                status="success"
                size="small"
                @click="anlysis(record)"
              >
                分析
              </a-button>

              <a-button
                type="text"
                status="default"
                size="small"
                @click="history(record)"
              >
                历史
              </a-button>
              <a-button
                type="text"
                status="success"
                size="small"
                @click="SurveyWithGroup(record)"
              >
                新建问卷
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 查看用户历史的部分 -->
    <a-card v-if="historyVisible == true" title="用户历史">
      <!--  返回的按钮  -->
      <a-button @click="backButton1"> 返回 </a-button>
      <!-- 真正展示数据 -->
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination1"
        :data="historyCon"
        :bordered="false"
        @page-change="onPageChange1"
      >
        <template #columns>
          <a-table-column title="群组名" data-index="groupname" />
          <a-table-column title="描述" data-index="description" />
          <a-table-column
            :title="$t('searchTable.columns.operations')"
            data-index="operations"
          >
            <!-- 获取一行的信息 -->
            <template #cell="record">
              <a-button
                type="text"
                status="warning"
                size="small"
                @click="deleteHistory(record)"
              >
                删除
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 这是新建的部分 -->
    <a-card v-if="createVisible == true" title="创建群组">
      <!--  返回的按钮  -->
      <a-button @click="backButton"> 返回 </a-button>
      <!-- 下面要展示的具体内容 就是创建群组的 -->
      <!--  最开始是输入一些必要的信息 -->
      <a-col>
        <!--  输入群组名称啥的的表格 -->
        <a-form :model="createGroup">
          <a-form-item field="groupname" label="群组名称">
            <a-input
              v-model="createGroup.groupname"
              placeholder="请输入群组名称……"
              style="width: 30%"
            ></a-input>
          </a-form-item>
          <a-form-item field="description" label="群组描述">
            <a-textarea
              v-model="createGroup.description"
              placeholder="请输入群组描述……"
              style="width: 60%"
            ></a-textarea>
          </a-form-item>
          <a-form-item>
            <a-button @click="createGroupButton"> 提交 </a-button>
          </a-form-item>
        </a-form>
      </a-col>
      <!--  分割线 -->
      <a-divider style="margin-top: 0" />
      <!-- 下面是添加用户到 列表 然后给后端传过去 -->

      <a-col>
        <!-- 左侧的所有答者列表 -->
        <div style="float: left" class="left">
          <div class="dazhe">全部答者列表</div>
          <a-table
            row-key="id"
            :loading="loading"
            :pagination="Respagination"
            :data="allRes"
            :bordered="false"
            @page-change="onPageChange"
          >
            <template #columns>
              <a-table-column title="答者名称" data-index="username" />
              <a-table-column
                :title="$t('searchTable.columns.operations')"
                data-index="operations"
              >
                <!-- 获取一行的信息 -->
                <template #cell="record">
                  <a-button
                    type="text"
                    status="warning"
                    size="small"
                    @click="addToRight(record)"
                  >
                    <!-- {{ $t('searchTable.columns.operations.view') }} -->
                    添加
                  </a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        <!-- 右侧的已选中的答者列表 -->
        <div style="float: right" class="right">
          <!-- 用个form吧 遍历展示 -->
          <div>选中答者列表</div>
          <a-list v-for="(item, index) in createGroup.usernames" :key="index">
            <!-- <template #header>
              已选中答者
            </template> -->
            <a-list-item>{{ item }}</a-list-item>
          </a-list>
        </div>
      </a-col>
    </a-card>

    <!-- 这是修改的部分 -->
    <a-card v-if="modifyVisible == true">
      <!--  返回的按钮  -->
      <a-button @click="modifyBackButton"> 返回 </a-button>
      <!-- 现在最上面展示名字和描述 -->
      <a-col>
        <!--  分割线 -->
        <a-divider style="margin-top: 0" />
        <!--  输入群组名称啥的的表格 -->
        <a-form :model="modifyGroupDetail">
          <a-form-item field="groupname" label="群组名称">
            <a-input
              v-model="modifyGroupDetail.groupname"
              style="width: 30%"
            ></a-input>
          </a-form-item>
          <a-form-item field="description" label="群组描述">
            <a-textarea
              v-model="modifyGroupDetail.description"
              style="width: 60%"
            ></a-textarea>
          </a-form-item>
          <a-form-item>
            <a-button @click="modifyGroupButton"> 提交 </a-button>
          </a-form-item>
        </a-form>
      </a-col>
      <!-- 在下面进行答者的选择 -->
      <a-col>
        <!-- 左侧的所有答者列表 -->
        <div style="float: left" class="left">
          <div class="dazhe">全部答者列表</div>
          <a-table
            row-key="id"
            :loading="loading"
            :pagination="Respagination"
            :data="allRes"
            :bordered="false"
            @page-change="onPageChange"
          >
            <template #columns>
              <a-table-column title="答者名称" data-index="username" />
              <a-table-column
                :title="$t('searchTable.columns.operations')"
                data-index="operations"
              >
                <!-- 获取一行的信息 -->
                <template #cell="record">
                  <a-button
                    type="text"
                    status="warning"
                    size="small"
                    @click="modifyAddToRight(record)"
                  >
                    <!-- {{ $t('searchTable.columns.operations.view') }} -->
                    添加
                  </a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        <!-- 右侧的已选中的答者列表 -->
        <div style="float: right" class="right">
          <!-- 用个form吧 遍历展示 -->
          <div>选中答者列表</div>
          <a-table
            row-key="id"
            :loading="loading"
            :pagination="Respagination"
            :data="modifyGroupMember"
            :bordered="false"
            @page-change="onPageChange"
          >
            <template #columns>
              <a-table-column title="答者名称" data-index="username" />
              <a-table-column title="操作" data-index="operations">
                <template #cell="record">
                  <a-button
                    type="text"
                    status="warning"
                    size="small"
                    @click="deleteToLeft(record)"
                  >
                    删除
                  </a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </a-col>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, createElementBlock } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {
    queryGroupList,
    PolicyRecord,
    PolicyParams,
    queryPolicyList,
    createGroupApi,
    deleteGroup,
    getGroupDeatail,
    modifyGroupToBack,
    respondentStatics,
    groupStatics,
  } from '@/api/list';
  import { useSurveyStore } from '@/store';
  import { useGroupIdFindHistory, useGroupIdDeleteHistory } from '@/api/user';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import uuid from '@/views/question-management/create-question/components/uuid';
  import { Message } from '@arco-design/web-vue';
  import router from '@/router';

  import questionDataSurveyStore from '@/store/modules/data-screen';

  const questionData = questionDataSurveyStore();

  const generateFormModel = () => {
    return {
      number: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);
  const formModel = ref(generateFormModel());
  const basePagination: Pagination = {
    page: 1,
    limit: 20,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const createVisible = ref(false);
  const modifyVisible = ref(false);
  // 控制主表格的显示
  const mainVisible = ref(true);
  // 用于修改的展示
  const modifyGroupDetail = ref({});
  // 历史的显示
  const historyVisible = ref(false);
  // 接收修改群组的已选中群组
  const modifyGroupMember = ref([]);

  // 修改群组的按钮
  const handleModify = async (record: any) => {
    mainVisible.value = false;
    modifyVisible.value = true;
    modifyGroupDetail.value = record.record;
    // 获取群组的id
    console.log(modifyGroupDetail.value);
    const params = {
      page: 0,
      size: 20,
      username: '',
      group_id: record.record.id,
      orderField: '',
      order: '',
    };
    const { data } = await getGroupDeatail({
      page: 0,
      size: 5,
      username: '',
      group_id: record.record.id,
      orderField: '',
      order: '',
    });
    console.log(data);
    // 已经有返回的选中答者的列表了，我得赋值到一个地方
    modifyGroupMember.value = data.list;
    console.log(modifyGroupMember.value);
  };

  // 这里开始写历史相关的
  // 针对历史的变量
  const historyCon = ref({});

  const anlysis = async (record) => {
    console.log('进来group分析了');
    console.log('进来group分析了');
    console.log('进来group分析了');
    console.log('进来group分析了');
    console.log('进来group分析了');
    const { data } = await groupStatics(record.record.id);

    console.log('data');
    console.log(data);
    console.log('data');

    questionData.group = data;
    console.log('questionData.group');
    console.log(questionData.group);
    console.log('questionData.group');
    // router.push({
    //   name: 'ScreenGroupData',
    // });
  };

  // 主页面发送请求的按钮
  const history = async (record: any) => {
    mainVisible.value = false;
    historyVisible.value = true;

    // 然后要发请求了
    const toBack = {
      page: 0,
      answerLimit: 10,
      groupId: record.record.id,
    };
    const { data } = await useGroupIdFindHistory(toBack);
    console.log('查询用户历史');
    console.log(data);
    // 这才是需要的 赋值
    console.log(data.list);
    historyCon.value = data.list;
  };
  // 删除历史
  const deleteHistory = async (record: any) => {
    console.log(record.record.id);
    await useGroupIdDeleteHistory([record.record.id]);
    Message.success('删除成功');
    // 再发一次查询历史的接口
    const toBack = {
      page: 0,
      answerLimit: 10,
      groupId: record.record.groupId,
    };
    const { data } = await useGroupIdFindHistory(toBack);
    historyCon.value = data.list;
  };

  // 返回的按钮
  const backButton1 = () => {
    mainVisible.value = true;
    historyVisible.value = false;
  };

  // 新建
  const handleCreate = () => {
    mainVisible.value = false;
    createVisible.value = true;
  };
  // 使用群组来创建问卷
  const SurveyWithGroup = (record) => {
    console.log(record.record);
    useSurveyStore().groupId = record.record.id;
    console.log(useSurveyStore().groupId);
    router.push({
      name: 'CreateSurvey',
    });
  };
  // 从这里开始写 创建群组
  const createGroup = ref({
    id: uuid.uuid(),
    groupname: '',
    description: '',
    //  用户的id
    userIds: [],
    usernames: [],
  });

  // 点击添加之后 左边的用户到右边
  const addToRight = (data: any) => {
    console.log(data.record.id);
    createGroup.value.userIds.push(data.record.id);
    createGroup.value.usernames.push(data.record.username);
    console.log(createGroup.value);
  };

  // 提交按钮了 往后发请求
  const createGroupButton = async () => {
    createGroupApi(createGroup.value);
  };

  // 获取所有答者 从别的页面学的
  const allRes = ref<PolicyRecord[]>([]);
  const Respagination = reactive({
    ...basePagination,
  });
  const role = '3';
  const fetchResData = async (
    params: PolicyParams = {
      page: 1,
      limit: 20,
      role: 3,
      isDeleted: '0',
    }
  ) => {
    setLoading(true);
    try {
      const { data } = await queryPolicyList(params);
      allRes.value = data.list;
      Respagination.page = params.page;
      Respagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 调用自己
  fetchResData();

  const fetchData = async (
    params: PolicyParams = {
      page: 1,
      limit: 20,
      role: 0,
      isDeleted: '0',
    }
  ) => {
    setLoading(true);
    try {
      // 这里调的接口 从这里改
      const { data } = await queryGroupList(params);
      // 看看回来了啥
      console.log('请求返回');
      console.log(data.list);

      renderData.value = data.list;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PolicyParams);
  };
  const onPageChange = (page: number) => {
    fetchData({ ...basePagination, page });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  // 返回的按钮
  const backButton = () => {
    console.log('返回主页');
    mainVisible.value = true;
    createVisible.value = false;
  };

  // 修改群组的返回按钮
  const modifyBackButton = () => {
    mainVisible.value = true;
    modifyVisible.value = false;
  };

  // 删除函数
  const deleteGroupButton = async (data: any) => {
    console.log(data.record.id);

    // 发送删除的请求
    // 不能直接传data
    deleteGroup([data.record.id]);
  };

  // 修改群组的部分
  const deleteToLeft = (record: any) => {
    const index = modifyGroupMember.value.indexOf(record.record);
    if (index > -1) {
      modifyGroupMember.value.splice(index, 1);
    }
  };

  //  修改群组中的 点击添加之后 左边的用户到右边
  const modifyAddToRight = (data: any) => {
    const temp = {
      birth: '',
      city: '北京',
      createDate: '',
      creator: null,
      email: null,
      gender: 1,
      header: '',
      id: '',
      isDeleted: '',
      job: '',
      managedBy: '',
      mobile: '',
      nickname: '',
      password: '',
      reserved: '',
      role: '',
      sign: '',
      sourceType: '',
      updateDate: '',
      updater: '',
      username: '',
    };
    temp.id = data.record.id;
    temp.username = data.record.username;
    modifyGroupMember.value.push(temp);
    console.log(modifyGroupMember.value);
  };

  // 修改群组的按钮 提交 需要写for循环
  const modifyGroupButton = async () => {
    // eslint-disable-next-line camelcase
    const user_id = [];
    // 提取出id
    for (let i = 0; i < modifyGroupMember.value.length; i += 1) {
      // eslint-disable-next-line camelcase
      user_id.push(modifyGroupMember.value[i].id);
    }

    const toBack = {
      // eslint-disable-next-line camelcase
      userIds: user_id,
      id: modifyGroupDetail.value.id,
      description: modifyGroupDetail.value.description,
      avatar: null,
      creator: null,
      reserved: null,
      groupname: modifyGroupDetail.value.groupname,
    };

    await modifyGroupToBack(toBack);
    Message.success('修改成功');
  };
</script>

<script lang="ts">
  export default {
    name: 'SearchTable',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .left {
    width: 30%;
    margin-left: 10%;
    background-color: aquamarine;
  }

  .right {
    width: 30%;
    margin-right: 10%;
    background-color: blanchedalmond;
  }

  .dazhe {
    size: 36px;
  }
</style>
